package com.kehao.leetcode.jzoffer;

import java.util.HashMap;
import java.util.Map;

public class JZSolution062 {

    private static class Trie {

        Map<Character,Map> map = new HashMap<>();

        /** Initialize your data structure here. */
        public Trie() {

        }

        /** Inserts a word into the trie. */
        public void insert(String word) {
            Map<Character,Map> pMap = map;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                pMap = pMap.computeIfAbsent(c,key->new HashMap<Character,Map>());
            }
            pMap.put((char) -1,null);
        }

        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            Map<Character,Map> pMap = map;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if(pMap.containsKey(c)){
                    pMap = pMap.get(c);
                }else {
                    return false;
                }
            }
            if(pMap.containsKey((char)-1)){
                return true;
            }else {
                return false;
            }
        }

        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            Map<Character,Map> pMap = map;
            for (int i = 0; i < prefix.length(); i++) {
                char c = prefix.charAt(i);
                if(pMap.containsKey(c)){
                    pMap = pMap.get(c);
                }else {
                    return false;
                }
            }
            return true;
        }
    }

}
